package com.starsky.common.utils.ssh;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;


/**
 * 使用jsch 调用远程服务器执行命令，并返回结果
 */
public class JSCHUtil {
    private static final JSCHUtil instance = new JSCHUtil();

    private static Session session;

    public static JSCHUtil getInstance() {
        return instance;
    }

    private Session connect(String host, int port, String ueseName, String password) throws Exception {
        session = getSession(host, port, ueseName);
        session.setPassword(password);

//在首次连接服务器时，会弹出公钥确认的提示。这会导致某些自动化任务，由于初次连接服务器而导致自动化任务中断。或者由于 ~/.ssh/known_hosts 文件内容清空，导致自动化任务中断。
// SSH 客户端的 StrictHostKeyChecking 配置指令，可以实现当第一次连接服务器时，自动接受新的公钥。只需要修改 /etc/ssh/ssh_config 文件,StrictHostKeyChecking no
        Properties config = new Properties();
        config.setProperty("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        this.session = session;

        return session;
    }

    public String execCmd(String command) throws Exception {
        if (session == null) {
            throw new RuntimeException("Session is null!");
        }

        ChannelExec exec = (ChannelExec) session.openChannel("exec");
        InputStream in = exec.getInputStream();
        exec.setCommand(command);
        exec.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuffer buffer = new StringBuffer();
        String line = reader.readLine();
        while (StringUtils.isNotBlank(line)) {
            buffer.append(line + "\r\n");
            line = reader.readLine();
        }
//        byte[] b = new byte[1024];
//        while (in.read(b) > 0) {
//            buffer.append(new String(b));
//        }
        exec.disconnect();

        return buffer.toString();
    }

    public static String exec(String host, int port, String ueseName, String password,String command ) throws Exception {
        JSCHUtil c = JSCHUtil.getInstance();
        try {
            instance.connect(host, port, ueseName, password);
            String str= instance.exec(command);
            System.out.println("str: " + str);
            retrur str;
        } catch (Exception e) {
            e.printStackTrace();
             retrur "执行命令异常："+e.getMessage();
        }finally{
             instance.close();
        }
    }


    public void clear(Session session) {
        if ((session != null) && session.isConnected()) {
            session.disconnect();
            session = null;
        }
    }

    public static void main(String[] args) throws Exception {
//        long begintime = System.currentTimeMillis();
//        Session session = JSCHUtil.getInstance().connect("192.168.0.157", 22, "root", "123456");
////		 String cmd = "cd /" + ";" + "ls -al |grep home";
//        String cmd = "cd /usr/local/" + ";" + "netstat -ntlp";
//        // 运算代码
//        String result = JSCHUtil.getInstance().execCmd(session, cmd); // ???????;??
//        long endtinme = System.currentTimeMillis();
//        long costTime = (endtinme - begintime);
//        System.out.println("总共用了" + costTime);
//        System.out.println("执行结果：" + result);
//        System.exit(0);

        try {

            String host = "47.119.120.197";
            int port = 22;
            String ueseName = "root";
            String password = "ds.123abc";
            String command = "/usr/local/mongodb-linux-x86_64-4.0.7//script/mongodb-server.sh restart";

            String str= JSCHUtil.execCmd(host, port, ueseName, password,command);
            System.out.println("str: " + str);
          
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
